<?php
namespace Common\Util;

class Wxrcode{

	/**
	 * 生成场景二维码
	 *
	 * @param $app_id
	 * @param $app_secret
	 * @param $scene
	 * @param $page_path
	 * @return false|string
	 */
	public static function getUserShareWxcode($app_id, $app_secret, $scene, $page_path){
		$dirPath = SITE_PATH.'Data/tempImage'.'/'.$app_id;
		!is_dir($dirPath) && mkdir($dirPath, 0755, true);

		$code_img_url = '/Data/tempImage/'.$app_id.'/'.md5($app_id.$scene.$page_path).'3.png';
		if(file_exists(SITE_PATH.$code_img_url)){
			return $code_img_url;
		}
		$access_token = cyz_getWxToken($app_id, $app_secret);
		$wx_getcode_url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
		$post_arr['scene'] = $scene;
		$post_arr['page'] = $page_path;
//		$post_arr['check_path'] = true;
//		$post_arr['env_version'] = 'trial';
		$post_arr['width'] = 430;
		$post_arr['auto_color'] = false;
		$post_arr['is_hyaline'] = false;

		$rcode_data = cyz_curl_post_contents($wx_getcode_url, json_encode($post_arr));
		$rcode_data_arr = json_decode($rcode_data, true);
		if(is_array($rcode_data_arr)){
			return false;
		}
		@file_put_contents(SITE_PATH.$code_img_url, $rcode_data);
		if(file_exists(SITE_PATH.$code_img_url)){
			return $code_img_url;
		}else{
			return false;
		}
	}

	/**
	 * 发送微信小程序订阅消息
	 *
	 * @param $user_openid
	 * @param $tem_id
	 * @param $page_url
	 * @param $tem_data
	 * @return bool
	 */
	public static function sendSubscribeMessage($user_openid, $tem_id, $page_url, $tem_data){
		$app_config = BaseData::getAppSetting();
		$access_token = cyz_getWxToken($app_config['wx_app_appid'], $app_config['wx_app_appsecret']);
		$request_url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;
		$requestData = [
			'touser'            => $user_openid,
			'template_id'       => $tem_id,
			'page'              => $page_url,
			'data'              => $tem_data,
			'miniprogram_state' => 'formal',
			'lang'              => 'zh_CN',
		];
		$rcode_data = cyz_curl_post_contents($request_url, json_encode($requestData));
		//        hx_write_app_log($rcode_data,'sub_msg_');
		return $rcode_data;
	}
}
